/*
 *
 * JavaScript - core
 */
// 设置激活菜单
function setSidebarActive(tagUri) {
    var liObj = $("#" + tagUri);
    if (liObj.length > 0) {
        liObj.parent().parent().addClass("active");
        liObj.addClass("active");
    }
}

(function($) {

    // 选择框
    $(".select2").select2();

    // WYSIHTML5编辑器
    $(".textarea").wysihtml5({
        locale: 'zh-CN'
    });

    // AJAX全局设置
    $.ajaxSetup({
        traditional: true
    });

    // 状态
    $(document).ajaxComplete(function(event, request, settings) {
        var validateStatus = request.getResponseHeader("validateStatus");
        var loginStatus = request.getResponseHeader("loginStatus");
        if (validateStatus == "accessDenied") {
            alert("非法字符");
        } else if (loginStatus == "accessDenied") {
            alert("登录超时，请重新登录");
            setTimeout(function() {
                location.reload(true);
            }, 2000);
        } else if (loginStatus == "unauthorized") {
            alert("对不起，您无此操作权限！");
        }
    });

    //插件
    $.fn.extend({
        // 文件上传
        uploader: function(options) {
            var settings = {
                url: base+'/admin/file/upload',
                fileName: "file",
                data: {},
                multiple:false,
                maxSize: 10,
                extensions: "jpg,jpeg,bmp,gif,png,swf,flv,mp3,wav,avi,rm,rmvb,zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx",
                before: null,
                complete: null
            };
            $.extend(settings, options);
            console.log('element',this)
            var $progressBar = $('<div class="progressBar"><\/div>').appendTo("body");
            return this.each(function() {
                var element = this;
                var $element = $(element);

                var webUploader = WebUploader.create({
                    swf: base+'/admin/static/plugins/webuploader/webuploader.swf',
                    server: settings.url,
                    pick: {
                        id: element,
                        multiple: false
                    },
                    fileVal: settings.fileName,
                    formData: settings.data,
                    fileSingleSizeLimit: settings.maxSize * 1024 * 1024,
                    accept: {
                        extensions: settings.extensions
                    },
                    fileNumLimit: 1,
                    auto: true
                }).on('beforeFileQueued', function(file) {
                    
                    if ($.isFunction(settings.before) && settings.before.call(element, file) === false) {
                        return false;
                    }
                    if ($.trim(settings.extensions) == '') {
                        this.trigger('error', 'Q_TYPE_DENIED');
                        return false;
                    }
                    this.reset();
                    $progressBar.show();
                }).on('uploadProgress', function(file, percentage) {
                    $progressBar.width(percentage * 100 + '%');
                }).on('uploadAccept', function(file, data) {
                    $progressBar.fadeOut("slow", function() {
                        $progressBar.width(0);
                    });
                    if (data.state != 'SUCCESS') {
                        alert(data.message);
                        return false;
                    }
                    var div = $element.closest(".data");
                    var type = div.attr("type");
                    var input = div.find("input:text");
                    if(type=="file"){
                        var html = '';
                        html+='<dl value="'+data.url+'">';
                        html+='<dt><a href="javascript:;"><img src="'+data.url+'" class="preview"/></a></dt>';
                        html+='<dd>删除</dd>';
                        html+='</dl>';
                        input.val(data.url);
                        div.find(".picbox").html(html);
                    }else if(type="multiFile"){
                        var html = '';
                        html+='<dl value="'+data.url+'">';
                        html+='<dt><a href="javascript:;"><img src="'+data.url+'" class="preview"/><input type="hidden" name="picValues" value="'+data.url+'"></a></dt>';
                        html+='<dd>删除</dd>';
                        html+='<dt><a href="javascript:;" class="toPicBefore" style="float:left;">向左</a>&nbsp;&nbsp;&nbsp;<a href="javascript:;" class="toPicAfter" style="float:right;">向右</a></dt>';
                        html+='</dl>';
                        var inputVal = input.val();
                        div.find("input:text").val(inputVal+","+data.url);
                        div.find(".picbox").append(html);
                    }
                    if ($.isFunction(settings.complete)) {
                        settings.complete.call(element, file, data);
                    }
                }).on('error', function(type) {
                    switch(type) {
                        case "F_EXCEED_SIZE":
                            alert("上传文件大小超出限制");
                            break;
                        case "Q_TYPE_DENIED":
                            alert("上传文件格式不正确");
                            break;
                        default:
                            alert("上传文件出现错误");
                    }
                });

                $element.mouseover(function() {
                    webUploader.refresh();
                });
            });
        },

        // 编辑器
        editor: function(options) {
            window.UEDITOR_CONFIG = {
                UEDITOR_HOME_URL: base+'/admin/static/plugins/ueditor/',
                serverUrl: base+'/admin/file/upload',
                imageActionName: "uploadImage",
                imageFieldName: "file",
                imageMaxSize: 10 * 1024 * 1024,
                imageAllowFiles: ['.jpg', '.jpeg', '.bmp', '.gif', '.png'],
                imageUrlPrefix: "",
                imagePathFormat: "",
                imageCompressEnable: false,
                imageCompressBorder: 1600,
                imageInsertAlign: "none",
                videoActionName: "uploadMedia",
                videoFieldName: "file",
                videoMaxSize: 10 * 1024 * 1024,
                videoAllowFiles: ['.swf', '.flv', '.mp3', '.wav', '.avi', '.rm', '.rmvb'],
                videoUrlPrefix: "",
                videoPathFormat: "",
                fileActionName: "uploadFile",
                fileFieldName: "file",
                fileMaxSize: 10 * 1024 * 1024,
                fileAllowFiles: ['.zip', '.rar', '.7z', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'],
                fileUrlPrefix: "",
                filePathFormat: "",
                toolbars: [[
                    'fullscreen', 'source', '|',
                    'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
                    'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                    'touppercase', 'tolowercase', '|',
                    'link', 'unlink', 'anchor', '|',
                    'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'insertvideo', 'attachment', 'map','insertcode', 'insertframe', 'pagebreak', '|',
                    'horizontal', 'date', 'time', 'spechars', '|',
                    'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
                    'print', 'preview', 'searchreplace', 'drafts'
                ]],
                lang: "zh_CN",
                iframeCssUrl: null,////给编辑器内部引入一个css文件
                pageBreakTag: 'page_break_tag',
                allowDivTransToP:false,
                autoHeightEnabled:false,
                wordCount: false
            };

            UE.Editor.prototype.getActionUrl = function(action) {
                var serverUrl = this.getOpt('serverUrl');
                switch(action) {
                    case "uploadImage":
                        return serverUrl;
                    case "uploadMedia":
                        return serverUrl;
                    case "uploadFile":
                        return serverUrl;
                }
                return null;
            };

            UE.Editor.prototype.loadServerConfig = function() {
                this._serverConfigLoaded = true;
            };

            return this.each(function() {
                var element = this;
                var $element = $(element);

                UE.getEditor($element.attr("id"), options).ready(function() {
                    this.execCommand("serverparam", {
                        csrfToken: getCookie("csrfToken")
                    });
                });
            });
        }

    });

})(jQuery);

//验证
if ($.validator != null) {

    $.extend($.validator.messages, {
        required: '必填',
        email: 'E-mail格式错误',
        url: '网址格式错误',
        date: '日期格式错误',
        dateISO: '日期格式错误',
        pointcard: '信用卡格式错误',
        number: '只允许输入数字',
        digits: '只允许输入零或正整数',
        minlength: $.validator.format('长度不允许小于{0}'),
        maxlength: $.validator.format('长度不允许大于{0}'),
        rangelength: $.validator.format('长度必须在{0}-{1}之间'),
        min: $.validator.format('不允许小于{0}'),
        max: $.validator.format('不允许大于{0}'),
        range: $.validator.format('必须在{0}-{1}之间'),
        accept: '输入后缀错误',
        equalTo: '两次输入不一致',
        remote: '输入错误',
        integer: '只允许输入整数',
        positive: '只允许输入正数',
        negative: '只允许输入负数',
        decimal: '数值超出了允许范围',
        pattern: '格式错误',
        extension: '文件格式错误'
    });

    $.validator.setDefaults({
        showErrors: function(errorMap, errorList) {
            for(i in errorMap){
                var title = $("#inputForm").find("*[name='"+i+"']").closest(".data").prev(".title:first").html();
                swal({title:'', text:title+errorMap[i],icon: 'error'});
                return;
            }
        },
        onfocusin:false,
        onfocusout:false,
        onclick:false,
        onkeyup:false,
        submitHandler: function(form) {
            form.submit();
        }
    });

}